import java.text.NumberFormat;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FormatUtils {
    public static def sortItems(items, property) {
        items.sort { a, b -> a."${property}" <=> b."${property}" }
    }

   public static String fillZerosLeft(String string, int length) {
      int stringLength = string.length();
      int numberZeros = length - stringLength;
      if (numberZeros >= 0) {
         for (int j = 0; j < numberZeros; j++) {
            string = "0" + string;
         }
      } else {
         return string;
      }
      return string;
   }
   public static String delZerosLeft(String cta){
      int enc=0;
      for(int i=0;i<cta.length();i++){
         if(cta.charAt(i)!='0'){
            enc=i;
            break;
         }
      }
      return cta.substring(enc,cta.length());
   }
   public static String formatoFecha(Date d){
      int M=d.getMonth()+1
      String dia=(d.getDate()<10)?'0'+d.getDate():''+d.getDate()
      String mes=(M<10)?'0'+M:''+M
      String an=1900+d.getYear()
      return dia+'-'+mes+'-'+an
   }

   public static String formatDateDDMMYYYY(Date d){
      int M=d.getMonth()+1
      String dia=(d.getDate()<10)?'0'+d.getDate():''+d.getDate()
      String mes=(M<10)?'0'+M:''+M
      String an=1900+d.getYear()
      return dia+"/"+mes+"/"+an
   }

   public static Date converToDate(String date){
      def d=new Date()
      d.setDate(new Integer(date.substring(0,2)))
      d.setMonth(new Integer(date.substring(3,5))-1)
      d.setYear(new Integer(date.substring(6,10))-1900)
      return d
   }

   public static String convertToDateYYYYMMDDHHMMSS(Date date)
   {
      return (date.getYear()+1900)+""+fillZerosLeft((date.getMonth()+1)+"",2)+""+fillZerosLeft((date.getDate())+"",2)+""+fillZerosLeft((date.getHours())+"",2)+""+fillZerosLeft((date.getMinutes())+"",2)+""+fillZerosLeft((date.getSeconds())+"",2)
   }
   public static String convertToDateYYYYMMDD(Date date)
   {
      return (date.getYear()+1900)+""+fillZerosLeft((date.getMonth()+1)+"",2)+""+fillZerosLeft((date.getDate())+"",2)
   }

   /**
    *la bandera hora indica si se le coloca la hora en 0 o en 24
    */
   public static Date convertToDateHora(String date,int hora){
      def d=new Date()
      d.setDate(new Integer(date.substring(0,2)))
      d.setMonth(new Integer(date.substring(3,5))-1)
      d.setYear(new Integer(date.substring(6,10))-1900)
      if(hora==24){
         d.setHours(23)
         d.setMinutes(59)
         d.setSeconds(59)

      }else{
         d.setHours(0)
         d.setMinutes(0)
         d.setSeconds(0)
      }
      return d
   }
   /**
    *la bandera hora indica si se le coloca la hora en 0 o en 24
    */
   public static Timestamp convertToTimeStamp(String date,int hora){
        
      if(hora==24){
         return new Timestamp(new Integer(date.substring(6,10))-1900,new Integer(date.substring(3,5))-1,new Integer(date.substring(0,2)),23,59,59,999)
      }
      return new Timestamp(new Integer(date.substring(6,10))-1900,new Integer(date.substring(3,5))-1,new Integer(date.substring(0,2)),0,0,0,0)
        
   }
   /*
    *Convierte un Date con Time en una fecha tipo sql
    **/
   public static String convertToStringDateTime(Date d){
      return ''+(d.getYear()+1900)+'-'+(d.getMonth()+1)+'-'+d.getDate()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds()
   }
   public static boolean isDouble(String text){
      try{
         Double.parseDouble(text);
      }catch(Exception e){
         return false;
      }
      return true;
   }
   public static String formatoMonto(double monto){
      monto+=0.0000001;
      String res=""+monto;
      return res.substring(0,res.indexOf('.')+3);
   }

   public static double formatearMontoCCE(String montoString) {
      double monto = 0;
      try {
         String entero = montoString.substring(0,montoString.length()-2);
         String decimal = montoString.substring(montoString.length()-2, montoString.length());

         monto = Double.parseDouble(entero + "." + decimal);
      } catch (Exception e) {
         //logger.error("Error formateando " + montoString, e);
      }
      return monto;
   }

   public static String formatoDouble(double monto){
      try {
         NumberFormat nf = NumberFormat.getInstance();
         nf.setMaximumFractionDigits(3);
         return nf.format(monto);
      } catch (Exception e) {
         e.printStackTrace();
         return null;
      }
   }

   /*
    * Recibe monto double y lo convierte a String de 15 caracteres con 2 decimales
    **/
   public static String convertirMonto(double monto) {
      String fmt = "0.00#";
      DecimalFormat df = new DecimalFormat(fmt);
      String MontoStr = df.format(monto);
      String val=MontoStr;
      String MontoEnviar = "";
      if(val.indexOf(".")>0){
         val=val.substring(0,val.indexOf(".")+3);
         for (int i = 0; i < val.length(); i++) {
            if(val.charAt(i)!='.')
            MontoEnviar+=val.charAt(i);
         }
      }else if(val.indexOf(",")>0){
         val=val.substring(0,val.indexOf(",")+3);
         for (int i = 0; i < val.length(); i++) {
            if(val.charAt(i)!=',')
            MontoEnviar+=val.charAt(i);
         }
      }else
      MontoEnviar = val+"00";
      int t=15-MontoEnviar.length();
      for (int i = 0; i < t; i++)
      MontoEnviar = "0" + MontoEnviar;
      return MontoEnviar;

      /*double valor_peq = 0.00000001;
      double rest=monto+valor_peq;
      String val=rest+"";
      val=val.substring(0,val.indexOf(".")+3);
      String MontoEnviar =val.replace(".", "");
      int t=15-MontoEnviar.length();
      for (int i = 0; i < t; i++)
      MontoEnviar = "0" + MontoEnviar;
      return MontoEnviar;*/
   }
   /**
    * Método para fomatear monto de longitud 15
    *
    * @param <code>String</code> montoString: El String que representa un monto
    *        de longitud 15
    * @return El monto en forma de <code>double</code>
    * */
   public static double formatearMontoCamara(String montoString) {
      double monto = 0;
      try {
         if (montoString.length() == 15) {
            String entero = montoString.substring(0, 13);
            String decimal = montoString.substring(13, 15);

            monto = Double.parseDouble(entero + "." + decimal);
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
      return monto;
   }

   /**
    * Método para formatear la fecha a java.sql.Date
    *
    * @param stringDate
    * @return Fecha en formato java.sql.Date
    */
   public static java.sql.Date convertirFecha(String stringDate) {
      SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
      java.sql.Date dateParsed = null;
      try {
         dateParsed = new java.sql.Date(df.parse(stringDate).getTime());
      } catch (ParseException e) {
         return new java.sql.Date(System.currentTimeMillis());
      }
      return dateParsed;
   }

   /**
    * Redondea un monto a dos decimales.
    **/
   public static double redondearMonto(double monto){
      return Math.round(monto*Math.pow(10,2))/Math.pow(10,2);
   }

   /**
    * Este método coloca espacios a la izquierda de un String
    *
    * @param string
    *            el String al que se le van a colocar espacios
    * @param length
    *            el tamaño del String con espacios a la derecha
    * @return el String recibido con espacios a la derecha hasta completar el
    *         tamaño solicitado o null
    */
   public static String fillSpacesRight(String string, int length) {
      int stringLength = string.length();
      int numberSpaces = length - stringLength;
      if (numberSpaces >= 0) {
         for (int j = 0; j < numberSpaces; j++) {
            string = string + " ";
         }
      } else {
         return string;
      }
      return string;
   }


   /**
    * Para dar formato AAAAMMDD a la fecha
    *
    * @param l
    * @return
    */
   public static String formatDate(long l) {
      SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
      //formatter.setTimeZone(TimeZone.getTimeZone("America/Caracas"));
      String dateString = formatter.format(l);
      return dateString;
   }

   public static boolean validarRegex(String regex,String cadena){
	Pattern patron = Pattern.compile(regex);
	Matcher m = patron.matcher(cadena);
	if(m.find()){
         return true;
	}else{
         return false;
      }
   }        
}